#!/bin/bash

# Shadowsocks服务管理脚本
# 使用方法: ./ss-manager.sh {start|stop|restart|status}

SS_SERVER="ss-server"  # Shadowsocks服务器命令
CONFIG_FILE="/etc/shadowsocks/config.json"  # Shadowsocks配置文件路径
PID_FILE="/var/run/shadowsocks.pid"  # PID文件路径
LOG_FILE="/var/log/shadowsocks.log"  # 日志文件路径

start() {
    if [ -f "$PID_FILE" ]; then
        echo "Shadowsocks is already running (PID: $(cat $PID_FILE))"
        exit 1
    fi
    
    echo "Starting Shadowsocks server..."
    $SS_SERVER -c $CONFIG_FILE -f $PID_FILE -d start >> $LOG_FILE 2>&1
    
    if [ $? -eq 0 ]; then
        echo "Shadowsocks started successfully (PID: $(cat $PID_FILE))"
    else
        echo "Failed to start Shadowsocks"
        exit 1
    fi
}

stop() {
    if [ ! -f "$PID_FILE" ]; then
        echo "Shadowsocks is not running"
        exit 1
    fi
    
    echo "Stopping Shadowsocks server..."
    kill -9 $(cat $PID_FILE)
    rm -f $PID_FILE
    
    echo "Shadowsocks stopped"
}

restart() {
    stop
    sleep 2
    start
}

status() {
    if [ -f "$PID_FILE" ]; then
        echo "Shadowsocks is running (PID: $(cat $PID_FILE))"
    else
        echo "Shadowsocks is not running"
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit 0